import { createRouter, createWebHistory } from 'vue-router';
import { isAuthenticated } from '../utils/auth';
import Login from '../views/Login.vue';
import Dashboard from '../views/Dashboard.vue';
import Home from '../views/routers/Home.vue';
import Links from '../views/routers/Links.vue';
import Table from '../views/routers/Table.vue';
import Panel from '../views/routers/table/Panel.vue';

const routes = [
  {
    path: '/login',
    name: 'Login',
    component: Login
  },
  {
    path: '/',
    name: 'Dashboard',
    component: Dashboard,
    meta: { requiresAuth: true }, // 需要身份验证
    children: [
      {
        path: 'home',
        name: 'Home',
        component: Home,
        meta: { requiresAuth: true } // 需要身份验证
      },
      {
        path: 'links',
        name: 'Links',
        component: Links,
        meta: { requiresAuth: true } // 需要身份验证
      },
      {
        path: 'table',
        name: 'Table',
        component: Table,
        meta: { requiresAuth: true }, // 需要身份验证
        children: [
          {
            path: 'panel',
            name: 'Panel',
            component: Panel,
            meta: { requiresAuth: true } // 需要身份验证
          }
        ]
      }
    ]
  }
];

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes
});

// 全局导航守卫
router.beforeEach((to, from, next) => {
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!isAuthenticated()) {
      next({
        path: '/login',
        query: { redirect: to.fullPath } // 将重定向目标路径传递给登录页面
      });
    } else {
      next();
    }
  } else {
    next();
  }
});

export default router;
